package com.example.hellodemo.broadcast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.hellodemo.R;

public class BroadActivity extends AppCompatActivity {
    private Button nextBtn;
    private TextView textView;
    private BroadcastReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broad);

        nextBtn = findViewById(R.id.broad1);
        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BroadActivity.this,Broad2Activity.class);
                startActivity(intent);

            }
        });

        textView = findViewById(R.id.broad2);

        // 广播监听器
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
               switch (intent.getAction()){
                   case "updateText":
                       textView.setText(intent.getStringExtra("title"));
                       break;
               }
            }
        };
        // 过滤
        IntentFilter filter = new IntentFilter();
        filter.addAction("updateText");
        // 注册广播
        LocalBroadcastManager.getInstance(BroadActivity.this).registerReceiver(receiver,filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除广播监听器
        LocalBroadcastManager.getInstance(BroadActivity.this).unregisterReceiver(receiver);
    }
}
